<template>
  <!--  发货计划-->
  <div class="content">
    <!--		<print :hidden="true" ref="patrolPull" :drawQr="barcodeObj"></print>-->
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">

        <el-form-item label="待发区仓位">
          <el-select v-model="searchParam.pendingId" placeholder="请选择待发区仓位" filterable clearable
                     style="width: 200px">
            <el-option v-for="(item, index) of storageAllList" :key="index"
                       :label="item.storageName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="调拨入仓位">
          <el-select v-model="searchParam.inStoreId" placeholder="请选择调拨入仓位" filterable
                     clearable style="width: 200px">
            <el-option v-for="(item, index) of storageAllList" :key="index"
                       :label="item.storageName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="出库业务类型">
          <el-select v-model="searchParam.type" filterable placeholder="请选择出库类型" style="width: 200px"
          >
            <el-option v-for="item in businessTypeList" :key="item.id" :label="item.name"
                       :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="客户">
          <el-select v-model="searchParam.customerId" placeholder="请选择客户" filterable clearable
                     style="width: 200px">
            <el-option v-for="(item, index) of cusList" :key="index" :label="item.customerName"
                       :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button  type="primary"  :icon="Plus" @click="handleAdd()">新建</el-button>
          <el-button type="primary" @click="printCodeClick"
                     :disabled="multipleSelection.length != 1">预捡配单打印
          </el-button>
          <el-button type="primary" @click="printClick"
                     :disabled="multipleFatherSelection.length == 0">打印
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" row-key="id" height="calc(100vh - 320px)"
                @expand-change="handleExpandChange" header-cell-class-name="witheTableHeader">
        <el-table-column width="45" align="center">
          <template #default="scope">
            <el-checkbox @change="handleSelectionChange(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column type="expand">
          <template #default="props">
            <div m="4">
              <el-table ref="tableCil" border size="small" :data="props.row.children"
                        header-cell-class-name="blueTableHeader" style="width: 100%;margin-left: 20px">

                <el-table-column width="45" align="center">
                  <template #default="scopes">
                    <el-checkbox @change="handleSelectionFatherChange(scopes.row)"/>
                  </template>
                </el-table-column>
                <el-table-column label="" type="index" width="80" align="center"/>
                <!--								<el-table-column prop="customerId" label="单号" width="250" align="center" />-->
                <el-table-column prop="materialName" label="物料" width="170" align="center"/>
                <el-table-column prop="count" label="需求数量" width="250" align="center"/>
                <el-table-column prop="stockCount" width="250" label="备料数量" align="center"/>
                <el-table-column prop="shipmentCount" width="250" label="发货数量" align="center"/>
                <el-table-column prop="minCount" width="250" label="最小包装数" align="center"/>
                <el-table-column prop="weight" width="250" label="重量" align="center"/>
                <el-table-column prop="status" width="250" label="单据状态" align="center">
                  <template #default="scope">
                    {{ getStatusList(scope.row.status) }}
                  </template>
                </el-table-column>
                <el-table-column prop="version" width="250" label="物料版本" align="center"/>
                <el-table-column prop="customerPoNo" width="250" label="客户PO号" align="center"/>
                <el-table-column prop="customerBatchNo" width="250" label="客户批次号" align="center"/>
                <el-table-column prop="traceCode" width="250" label="追溯码" align="center"/>
                <el-table-column prop="batch" width="250" label="批次" align="center"/>
                <el-table-column prop="terminalMaterialCode" width="250" label="终端物料号码" align="center"/>
                <el-table-column prop="customerMaterialCode" width="250" label="客户物料号码" align="center"/>
                <el-table-column prop="description" width="250" label="客户物料描述" align="center"/>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 -->
            {{ (pageSearch.current - 1) * pageSearch.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="sn" label="单号" align="center" min-width="200"/>
        <el-table-column prop="pickingWarehouseName" label="拣货仓库" min-width="200" align="center"/>
        <el-table-column prop="pendingName" label="待发区" min-width="200" align="center"/>
        <el-table-column prop="inStoreName" min-width="200" label="调拨入仓位" align="center"/>
        <el-table-column prop="type" label="出库业务类型" align="center" min-width="200">
          <template #default="scope">
            <span> {{ getQualityTypeByValue(scope.row.type) }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" width="250" label="单据状态" align="center">
          <template #default="scope">
            {{ getStatusList(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户" width="250" align="center"/>
        <el-table-column prop="shipmentTime" label="发货日期" width="250" align="center"/>
        <el-table-column prop="receivingPerson" label="收货人" width="250" align="center"/>
        <el-table-column prop="phone" label="收货人联系方式" width="250" align="center"/>
        <el-table-column prop="targetSite" label="交货地址" width="250" align="center"/>
        <el-table-column prop="remark" label="备注" width="250" align="center"/>
        <el-table-column prop="createTime" label="创建时间" width="250" align="center"/>

        <el-table-column label="操作" align="center" fixed="right" width="150">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row,true)" type="text" size="small" plain v-if="scope.row.status == 1">
              编辑
            </el-button>
            <el-button @click="handleEdit(scope.row,false)" type="text" size="small" plain v-if="scope.row.status != 1">
              查看
            </el-button>
            <el-button @click="handleConfirm(scope.row)" type="text" size="small" plain v-if="scope.row.status == 1">确认
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current"
                       v-model:page-size="pageSearch.pageSize" :page-sizes="[10, 20, 50, 100, 200, 500]"
                       layout="total, sizes, prev, pager, next" :total="pageTotal" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 弹窗表单 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width="95%" top="5vh">
      <el-form :model="formData" label-width="auto" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="单据号" prop="sn">
              <el-input v-model="formData.sn" :disabled="!canEdit" style="width: 300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="拣货仓库" prop="pickingWarehouseId">
              <el-select v-model="formData.pickingWarehouseId" :disabled="!canEdit" placeholder="拣货仓库" filterable
                         clearable
                         style="width: 300px" @change="pickingWarehouseChange">
                <el-option v-for="(item, index) of wareList" :key="index"
                           :label="item.warehouseName" :value="item.id"/>
              </el-select>
              <!--							<el-tree-select v-model="formData.pickingWarehouseId" :data="wareList" check-strictly filterable-->
              <!--															:disabled="!canEdit" placeholder="请选择拣货仓库"-->
              <!--															:render-after-expand="false" :props="{-->
              <!--							children: 'sonList',-->
              <!--							label: 'warehouseName',-->
              <!--							value: 'id',-->
              <!--						}" style="width: 300px" @change="wareChange(formData.pickingWarehouseId,'pickingList')" />-->
            </el-form-item>
          </el-col>
          <!--					<el-col :span="6">-->
          <!--						<el-form-item label="拣货仓位" prop="pickingId">-->
          <!--							<el-select v-model="formData.pickingId" placeholder="请选择拣货仓库" filterable clearable-->
          <!--												 style="width: 300px" :disabled="!canEdit" @change="pickingIdChange">-->
          <!--								<el-option v-for="(item, index) of pickingList" :key="index"-->
          <!--													 :label="item.storageName" :value="item.id" />-->
          <!--							</el-select>-->
          <!--						</el-form-item>-->
          <!--					</el-col>-->
          <el-col :span="6">
            <el-form-item label="待发仓库">
              <el-tree-select v-model="formData.pendingWarehouseId" :disabled="!canEdit" :data="wareList" check-strictly
                              filterable
                              :render-after-expand="false"
                              placeholder="请选择待发仓库"
                              :props="{
							children: 'sonList',
							label: 'warehouseName',
							value: 'id',
						}" style="width: 300px" @change="wareChange(formData.pendingWarehouseId,'pendingList')"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="待发区" required prop="pendingId">
              <el-select v-model="formData.pendingId" :disabled="!canEdit" placeholder="请选择待发区" filterable clearable
                         style="width: 300px">
                <el-option v-for="(item, index) of pendingList" :key="index"
                           :label="item.storageName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出库业务类型" required prop="type">
              <el-select v-model="formData.type" filterable placeholder="请选择出库类型" style="width: 300px"
                         @change="typeChange" :disabled="!canEdit">
                <el-option v-for="item in businessTypeList" :key="item.id" :label="item.name"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调拨入仓库" :required="formData.type == 2" prop="inWarehouseId">
              <el-tree-select v-model="formData.inWarehouseId" :data="wareList" placeholder="请选择调拨入仓库"
                              :disabled="formData.type == 1 || !canEdit" check-strictly filterable
                              :render-after-expand="false" :props="{
							children: 'sonList',
							label: 'warehouseName',
							value: 'id',
						}" style="width: 300px" @change="wareChange(formData.inWarehouseId,'inWarehouseList')"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="调拨入仓位" :required="formData.type == 2" prop="inWarehouseId">
              <el-select v-model="formData.inStoreId" placeholder="请选择调拨入仓位" filterable
                         :disabled="formData.type == 1 || !canEdit"
                         clearable style="width: 300px">
                <el-option v-for="(item, index) of inWarehouseList" :key="index"
                           :label="item.storageName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户" required>
              <el-select v-model="formData.customerId" placeholder="请选择客户" filterable clearable
                         :disabled="formData.type != 1 || !canEdit" style="width: 300px">
                <el-option v-for="(item, index) of cusList" :key="index" :label="item.customerName"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发货日期" required prop="shipmentTime">
              <el-date-picker v-model="formData.shipmentTime" type="date" value-format="x"
                              placeholder="选择发货日期" style="width: 300px" :disabled="!canEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="收货人">
              <el-input v-model="formData.receivingPerson" style="width: 300px" :disabled="!canEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="收货人联系方式">
              <el-input v-model="formData.phone" style="width: 300px" :disabled="!canEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="交货地址">
              <el-input v-model="formData.targetSite" style="width: 300px" :disabled="!canEdit"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" :rows="2" type="textarea" style="width: 97%" :disabled="!canEdit"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="pageTableMenuView">
          <div class="pageTableTitle">物料明细</div>
          <div class="pageTableButView">
          </div>
        </div>
        <el-table class="pageTableClass" :data="workDetailData" border row-key="id" height="400px">
          <el-table-column label="序号" align="center" type="index" width="65"/>
          <el-table-column prop="name" label="物料" align="center" min-width="300">
            <template #default="scope" v-if="canEdit">
              <el-select v-model="scope.row.sourceId" placeholder="请选择物料" clearable filterable :disabled="!canEdit"
                         style="width: 100%" @change="detailMaterialChange(scope.$index)">
                <el-option v-for="item in inventoryList" :key="item.id" :label="item.materialName"
                           :value="item.id">
                  <div style="display: flex;justify-content: flex-start;">
                    <div style="width: 200px;">{{ item.materialName }}</div>
                    <div
                        style="width: 200px; color: var(--el-text-color-secondary);font-size: 13px;">
                      {{ item.batchNo }}
                    </div>
                    <div
                        style="width: 100px; color: var(--el-text-color-secondary);font-size: 13px;">
                      数量：{{ item.count }}
                    </div>
                    <div
                        style="width: 200px; color: var(--el-text-color-secondary);font-size: 13px;">
                      {{ item.batch }}
                    </div>
                  </div>
                </el-option>
              </el-select>
            </template>
            <template #default="scope" v-else>
              {{ scope.row.materialNo }}
            </template>
          </el-table-column>
          <el-table-column prop="count" label="需求数量" align="center" min-width="180">
            <template #default="scope">
              <el-input-number v-model="scope.row.count" @change="countChange(scope.$index)" :disabled="!canEdit"/>
            </template>
          </el-table-column>
          <!--					<el-table-column prop="shipmentTime" label="发货日期" align="center" min-width="230">-->
          <!--						<template #default="scope">-->
          <!--							<el-date-picker v-model="scope.row.shipmentTime" type="date" value-format="x"-->
          <!--															placeholder="选择发货日期" />-->
          <!--						</template>-->
          <!--					</el-table-column>-->

          <el-table-column prop="stockCount" label="备料数量" align="center" min-width="180" v-if="isEdit">
            <!--            <template #default="scope">-->
            <!--              <el-input-number v-model="scope.row.stockCount"/>-->
            <!--            </template>-->
          </el-table-column>
          <el-table-column prop="shipmentCount" label="发货数量" align="center" min-width="180" v-if="isEdit">
            <!--            <template #default="scope">-->
            <!--              <el-input-number v-model="scope.row.shipmentCount"/>-->
            <!--            </template>-->
          </el-table-column>
          <el-table-column prop="minCount" label="最小包装数" align="center" min-width="210">
            <template #default="scope">
              <el-input-number v-model="scope.row.minCount" :disabled="!canEdit" style="width: 100%"/>
            </template>
          </el-table-column>
          <el-table-column prop="minCount" label="备件数 " align="center" min-width="210">
            <template #default="scope">
              <el-input-number v-model="scope.row.sparePartsNumber" :disabled="!canEdit" style="width: 100%"/>
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量（KG）" align="center" min-width="210">
            <template #default="scope">
              <el-input-number v-model="scope.row.weight" :disabled="!canEdit" :min="0" style="width: 100%"/>
            </template>
          </el-table-column>
          <el-table-column prop="customerBatchNo" label="客户批次号" align="center" min-width="180">
            <template #default="scope">
              <el-input v-model="scope.row.customerBatchNo" :disabled="!canEdit" :min="0"/>
            </template>
          </el-table-column>
          <el-table-column prop="customerPoNo" label="客户PO号" align="center" min-width="180">
            <template #default="scope">
              <el-input v-model="scope.row.customerPoNo" :disabled="!canEdit"/>
            </template>
          </el-table-column>
          <el-table-column prop="shipmentTime" label="发货日期" align="center" min-width="230">
            <template #default="scope">
              <el-date-picker v-model="scope.row.shipmentTime" type="date" value-format="x"
                              placeholder="选择发货日期" style="width: 200px" :disabled="!canEdit"/>
            </template>
          </el-table-column>
          <el-table-column prop="batch" label="批次" align="center" min-width="230" show-overflow-tooltip/>
          <el-table-column prop="traceCode" label="追溯码" align="center" min-width="230" show-overflow-tooltip/>
          <el-table-column prop="version" label="物料版本" align="center" min-width="230" show-overflow-tooltip/>
          <el-table-column prop="terminalMaterialCode" label="终端物料号码" align="center" min-width="180">
            <!--            <template #default="scope">-->
            <!--              <el-input v-model="scope.row.terminalMaterialCode"/>-->
            <!--            </template>-->
          </el-table-column>
          <el-table-column prop="customerMaterialCode" label="客户物料号码" align="center" min-width="180">
            <!--            <template #default="scope">-->
            <!--              <el-input v-model="scope.row.customerMaterialCode"/>-->
            <!--            </template>-->
          </el-table-column>
          <el-table-column prop="description" label="客户物料描述" align="center" min-width="180">
            <!--            <template #default="scope">-->
            <!--              <el-input v-model="scope.row.description"/>-->
            <!--            </template>-->
          </el-table-column>

          <!--					<el-table-column prop="planCount" label="物料版本" align="center" min-width="180">-->
          <!--						<template #default="scope">-->
          <!--							<el-input v-model="scope.row.planCount" />-->
          <!--						</template>-->
          <!--					</el-table-column>-->
          <!-- <el-table-column prop="batch" label="批次" align="center" min-width="180">
            <template #default="scope">
              <el-input v-model="scope.row.batch" />
            </template>
          </el-table-column> -->
          <!--					<el-table-column prop="planCount" label="备品" align="center" min-width="180">-->
          <!--						<template #default="scope">-->
          <!--							<el-input v-model="scope.row.planCount" />-->
          <!--						</template>-->
          <!--					</el-table-column>-->
          <!--					<el-table-column prop="planCount" label="备注" align="center" min-width="180">-->
          <!--						<template #default="scope">-->
          <!--							<el-input v-model="scope.row.planCount" />-->
          <!--						</template>-->
          <!--					</el-table-column>-->
          <el-table-column label="操作" align="center" fixed="right" width="150" v-if="canEdit">
            <template #header="scope">
              <el-button type="text" size="small" :icon="Plus" @click="addWorkOrderDetail">新建</el-button>
            </template>
            <template #default="scope">
              <el-button @click="delWorkOrderDetail(scope.$index)" text type="danger" size="small"
                         :icon="Delete">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {computed, getCurrentInstance, reactive, ref} from 'vue';
//弹出层标题
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Plus, Refresh, Search, Setting} from '@element-plus/icons-vue';
import {parseGeoJSON} from 'echarts';

// import print from '@/components/Print/deliverGoodsPlan/print.vue';

onMounted(() => {
  getList();
  getOption();
});


const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const configTableShow = ref(false);

const handleClick = (e) => {
  console.log(e, 'handleClick');
};
// 配置质检项表
const configTable = ref([]);


// no usages
// NEW( code:1,name: "新建")
// no usages
// CONFIRM( code: 2,name:"已确认")
// no usagesPARTIAL_MATERIAL( code: 3,name:"部分备料")
// no usages
// PREPARED( code: 4，name:"已备料")
// no usages
// PARTIAL_DELIVERY( code: 5,name:"部分发货")
// 1 usage
// DELIVERY( code: 6,name:"已发货")
// no usages
// CANCEL( code: 9,name:"取消")
const statusList = ref([{
  value: 1,
  label: '新建'
}, {
  value: 2,
  label: '已确认'
}, {
  value: 3,
  label: '部分备料'
}, {
  value: 4,
  label: '已备料'
}, {
  value: 5,
  label: '部分发货'
}, {
  value: 6,
  label: '已发货'
}, {
  value: 9,
  label: '取消'
}
]);

// 可适用物料
const materialTable = ref([]);


const rowInfo = ref({});


const workOrderList = ref({});

const showMaterial = ref(false);
// 质检列表
const isConfigEdit = ref(false);

const isConfigIndex = ref(null);


const workDetailData = ref([{weight: 0}]);

const workOrderChange = (e) => {
  if (!e) {
    formData.materialNo = null;
    formData.materialId = null;
    formData.planNo = null;
    formData.planId = null;
    return false;
  }

  for (const item of workOrderList.value) {
    if (item.id == e) {
      formData.materialNo = item.materialNo;
      formData.materialId = item.materialId;
      formData.planNo = item.planNo;
      formData.planId = item.planId;
    }
  }
  // axiosInstance.post('/api/outsourcingPlan/queryByWorkMaterial', { id: e })
  // 	.then(res => {
  // 		if (res.code !== 200) {
  // 			ElMessage.error(res.message);
  // 			return false;
  // 		}
  // 		formData.count = res.data.orderCount;
  // 		formData.materialId = res.data.materialId;
  // 		formData.productId = res.data.productId;
  // 		materiaList.value = res.data.materialIdList;
  // 	});
};

const addWorkOrderDetail = () => {
  const list = {weight: 0}
  if (formData.shipmentTime) {
    list.shipmentTime = formData.shipmentTime;
  }
  workDetailData.value.push(list);
};


const delWorkOrderDetail = (e) => {
  workDetailData.value.splice(e, 1);
};


// 通用更新接口函数
const handleUpdateQualityScheme = (updatedRowInfo) => {
  axiosInstance.put('/api/basedataQualityScheme/update', updatedRowInfo).then(res => {
    if (res.code != 200) {
      ElMessage.error(res.message);
      return false;
    }
    ElMessage.success('操作成功!');
    showConfig.value = false;
    showMaterial.value = false;
    // 刷新配置质检项列表
    getList();
  });
};

const expandedRowKeys = ref<string[]>([]);

const handleExpandChange = (row: any, expandedRows: any[]) => {
  if (expandedRows.includes(row)) {
    rowChildren(row);
  } else {
    // getList();
  }
};

const rowChildren = (row: any) => {
  axiosInstance.post('/api/shipmentPlanDetail/getAll', {shipmentPlanId: row.id}).then(res => {
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return false;
    }
    const childrenWithTraceability = res?.data.map(child => ({
      ...child
    })) || [];
    paginatedData.value = paginatedData.value.map((item) => {
      if (item.id === row.id) {
        return {...item, children: childrenWithTraceability};
      }
      return item;
    });
    console.log(paginatedData.value);
  });
};


const pageTotal = ref(null);//页面总数
// const formData = reactive({});//form表单
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({});//页面检索条件
const showConfig = ref(false);
const configData = ref({});
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});

// 质检方式
const qualityWayList = reactive([
  {
    label: '全检',
    value: '1'
  }, {
    label: '比例抽检',
    value: '2'
  }, {
    label: '固定抽检',
    value: '3'
  }, {
    label: '自定义抽检',
    value: '4'
  }
]);


// 判断质检类型
const getQualityTypeByValue = (e) => {
  let name = null;
  for (const item of businessTypeList.value) {
    if (e == item.id) {
      name = item.name;
    }
  }
  return name;
};

const getStatusList = (e) => {
  let name = null;
  for (const item of statusList.value) {
    if (e == item.value) {
      name = item.label;
    }
  }
  return name;
}

const multipleFatherSelection = ref([]);

const handleSelectionFatherChange = (val) => {
  if (multipleFatherSelection.value.includes(val)) {
    // 如果 multipleSelection 已经包含 val，则删除它
    multipleFatherSelection.value = multipleFatherSelection.value.filter(item => item !== val);
  } else {
    // 如果 multipleSelection 不包含 val，则添加它
    multipleFatherSelection.value.push(val);
  }
};

const multipleSelection = ref([]);

const handleSelectionChange = (val) => {
  if (multipleSelection.value.includes(val)) {
    // 如果 multipleSelection 已经包含 val，则删除它
    multipleSelection.value = multipleSelection.value.filter(item => item !== val);
  } else {
    // 如果 multipleSelection 不包含 val，则添加它
    multipleSelection.value.push(val);
  }
};

// 质检类型
const qualityTypeList = reactive([
  {
    label: '部分送货',
    value: '1'
  },
  {
    label: '全部送货',
    value: '2'
  },
  {
    label: '未送货',
    value: '0'
  }
  // 继续添加更多检查类型...
]);

const ruleFormRef = ref<FormInstance>();

interface RuleForm {
  name: string;
  code: string;
  qualityWay: string;
  proportionNumber: string;
  qualityNumber: string;
  qualityType: string;
  qualityInterval: number;
  qualityIsLive: boolean;
  qualityRemark: string;
}


const originalFormData = reactive<RuleForm>({
  name: '',
  code: '',
  qualityWay: null,
  proportionNumber: 1,
  qualityNumber: 1,
  qualityType: '',
  qualityInterval: 1,
  qualityIsLive: true,
  qualityRemark: '',
  pendingWarehouseId: null,
  inWarehouseId: null,
  pickingWarehouseId: null,
  inStoreId: null
});

let formData = reactive<RuleForm>(originalFormData);


const rules = reactive<FormRules<formData>>({
  pendingId: [
    {required: true, message: '请选择待发区', trigger: 'blur'}
  ],
  inWarehouseId: [
    {required: true, message: '请选择调拨入仓库', trigger: 'blur'}
  ],
  type: [
    {required: true, message: '请选择出库业务类型', trigger: 'blur'}
  ],
  shipmentTime: [
    {required: true, message: '请选择发货日期', trigger: 'blur'}
  ],
  customerId: [
    {required: true, message: '请选择客户', trigger: 'blur'}
  ],
  sn: [
    {required: true, message: '请输入单据号', trigger: 'blur'}
  ],
  pickingWarehouseId: [
    {required: true, message: '请选择拣货仓库', trigger: 'blur'}
  ]
});


// const paginatedData = reactive([])//列表数据
const paginatedData = ref<RuleForm[]>([]);

const materiaList = ref([]);//物料表
const wareList = ref([]);//仓库
const procedureOrderList = ref([]);//工序订单
const supplierList = ref([]);
const storageAllList = ref([]);
// 供应商远端搜索
const supplierSearch = async (query: string) => {
  if (query) {
    try {
      const response = await axiosInstance.post(`/api/basedataSupplier/getPage`, {
        current: 1,
        pageSize: 20,
        name: query
      });
      supplierList.value = await response.data.records; // 假设返回的数据直接是供应商列表
    } catch (error) {
      supplierList.value = []; // 出错时清空列表
    }
  }
};

const pickingIdChange = (e) => {
  if (e) {
    workDetailData.value = [{weight: 0}];
    axiosInstance.post('/api/warehouseStorageMaterial/pageByPojo', {current: 1, pageSize: 9999999, storageId: e})
        .then(res => {
          inventoryList.value = res.data.records;
        });
  }
};

const pendingList = ref([]);
const pickingList = ref([]);
const inWarehouseList = ref([]);
const pickingWarehouseChange = (e) => {
  if (e) {
    workDetailData.value = [{weight: 0}];
    axiosInstance.post('/api/warehouseStorageMaterial/pageByPojo', {
      materialStatus: 1,
      current: 1,
      pageSize: 9999999,
      warehouseId: e
    })
        .then(res => {
          inventoryList.value = res.data.records;
        });
  }
};
const wareChange = (e, name) => {
  axiosInstance.post('/api/basedataStorage/listByPojoPage', {
    warehouseId: e,
    current: 1,
    pageSize: 999999
  })
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        switch (name) {
          case 'pendingList':
            pendingList.value = res.data.records;
            break;
          case 'pickingList':
            pickingList.value = res.data.records;
            break;
          case 'inWarehouseList':
            inWarehouseList.value = res.data.records;
            break;
        }
      });
};

const typeChange = () => {
  formData.inWarehouseId = null;
};

const businessTypeList = ref([
  {
    name: '销售出库',
    id: 1
  }, {
    name: '调拨（出）',
    id: 2
  }
  // , {
  // 	name: '委外出库',
  // 	id: 3
  // }, {
  // 	name: '线边备料（出）',
  // 	id: 4
  // }, {
  // 	name: '生产出库',
  // 	id: 5
  // }, {
  // 	name: '生产退库（出）',
  // 	id: 6
  // }
]);

const cusList = ref([]);
const inventoryList = ref([]);
const getOption = () => {
  axiosInstance.post('/api/outsourcingPlan/querySourcingPlanProcedureOrder', {})
      .then(res => {
        workOrderList.value = res.data;
      });


  // 客户
  axiosInstance.post('/api/customer/getPage', {current: 1, pageSize: 999999})
      .then(res => {
        cusList.value = res.data.records;
      });

  // 查询所有库位
  axiosInstance.post('/api/basedataStorage/getAll', {})
      .then(res => {
        storageAllList.value = res.data;
      });


  // 供应商
  axiosInstance.post(`/api/basedataSupplier/getPage`, {
    current: 1,
    pageSize: 20
  }).then(res => {
    if (res.code == 200) {
      supplierList.value = res.data.records;
    }
  });

  // 物料
  axiosInstance
      .post('/api/basedata/material/getPage', {current: 1, pageSize: 50}).then(res => {
    if (res.code == 200) {
      materiaList.value = res.data.records;
    }
  });

  axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    wareList.value = res.data;
  });
};

const warehouseChange = (e) => {
  axiosInstance.post('/api/warehouseStorageMaterial/queryByWarehouseId', {
    storageId: e,
    materialStatus: 1,
    procedureOrderId: formData.procedureOrderId
  })
      .then(res => {
        materiaList.value = res.data;
      });
};

const detailMaterialChange = (e) => {
  for (const item of inventoryList.value) {
    if (item.id == workDetailData.value[e].sourceId) {
      workDetailData.value[e].traceCode = item.traceabilityCode;
      workDetailData.value[e].traceabilityCodePlace = item.traceabilityCodePlaceIndex;
      workDetailData.value[e].materialBatchNo = item.batchNo;
      workDetailData.value[e].batchNo = item.batchNo;
      workDetailData.value[e].materialId = item.materialId;
      workDetailData.value[e].count = item.count;
      workDetailData.value[e].version = item.version;
      workDetailData.value[e].batch = item.batch;
    }
  }

  if (!formData.customerId) {
    workDetailData.value[e].lineWeight = null;
    return false;
  }
  axiosInstance.post('/api/customerMaterial/getPage', {
    current: 1,
    pageSize: 10,
    materialId: workDetailData.value[e].materialId,
    customerId: formData.customerId
  }).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    if (res.data.records.length > 0) {
      const item = res.data.records[0];
      workDetailData.value[e].customerMaterialCode = item.customerMaterialCode;
      workDetailData.value[e].terminalMaterialCode = item.terminalMaterialCode;
      workDetailData.value[e].description = item.description;
      workDetailData.value[e].lineWeight = item.weight;
      if (workDetailData.value[e].count) {
        countChange(e);
      }
      // workDetailData.value[e].weight = item.weight;
    }
  });

};

const barcodeObj = ref({});

// 获取列表接口
const getList = () => {
  paginatedData.value = [];
  multipleSelection.value = [];
  multipleFatherSelection.value = [];
  axiosInstance.post('/api/shipmentPlan/getPage', {
    ...searchParam.value,
    ...pageSearch.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records.map((item) => ({
          ...item,
          children: [],
          layer: 1,
          _loading: false
        }));
        console.log(paginatedData.value);
        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  // current.value = 1
  getList();
};

const countChange = (index) => {
  const list = JSON.parse(JSON.stringify(workDetailData.value));
  if (list[index].lineWeight) {
    list[index].weight = parseFloat((list[index].count * list[index].lineWeight).toFixed(10));
  }

  workDetailData.value = JSON.parse(JSON.stringify(list));
};


// 点击新建
const handleAdd = () => {
  isEdit.value = false;
  canEdit.value = true;
  // ruleFormRef.value.resetFields()
  formData = reactive({
    pendingWarehouseId: '9015fd15faac32a70dd1520a2323459b',
    pendingId: 'e7e515eb5365ee0ba60e87acc08f5522'
  });
  wareChange(formData.pendingWarehouseId, 'pendingList');
  workDetailData.value = [{weight: 0}];
  showCrud.value = true;
};

const {proxy}: any = getCurrentInstance();
// 打印
const printClick = () => {
  let info = multipleFatherSelection.value[0]
  let templateName = 'test_print1/DeliveryplanTagPrint.cpt';
  if (info.customerName == '雅达电子（罗定）有限公司') {
    templateName = 'test_print1/DeliveryplanTagPrint_10326.cpt'
  }

  if (info.customerName == '赛尔康技术（深圳）有限公司') {
    templateName = 'test_print1/StockinBarcodePrint_Default_test.cpt'
  }
  proxy.$printClick(templateName, multipleFatherSelection.value);
};

// import print from "@/components/Print/deliverGoodsPlan/print.vue";
// 打印
const printCodeClick = () => {
  axiosInstance.post('/api/shipmentPlan/print', {id: multipleSelection.value[0].id})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
      });

  console.log(multipleSelection.value);
  const templateName = 'test_print1/PreOnspectionForm.cpt';
  proxy.$printClick(templateName, multipleSelection.value);

  return
  // barcodeObj.value = result.data;
  const arr = [];
  // let list = result.data.ttDeliveryplanDtls;
  let list = [
    {
      name: 'aa',
      sex: '0',
      nums: 1
    },
    {
      name: 'bb',
      sex: '1',
      nums: 2
    },
    {
      name: 'cc',
      sex: '0',
      nums: 3
    },
    {
      name: 'dd',
      sex: '1',
      nums: 4
    }
  ];
  let filterFields = function (res) {
    return res.materialCode;
  };
  let newsArry = groupBy(list, filterFields);
  newsArry.forEach((el, index) => {
    console.log(el);
    let obj = {
      customerPoNo: '合计',
      materialQty: '0'
    };
    let nums = 0;
    el.forEach((item) => {
      nums += Number(item.materialQty);
    });
    obj.materialQty = nums;
    el.push(obj);
  });
  console.log(newsArry, 'newsArry');
  let news = [];
  newsArry.forEach((pp) => {
    pp.forEach((oo) => {
      news.push(oo);
    });
  });
  barcodeObj.value.newList = news;
  setTimeout(() => {
    // _that.patrolPullTlag = true;
    _that.$print(_that.$refs.patrolPull);
    _that.$refs.patrolPull.qrcode();
  }, 1000);
  // this.$api
  // 	.post(this.$lesUiPath.prepareSheetPrint, {
  // 		id: this.recordObjList[0].id,
  // 	})
  // 	.then((result) => {
  // 		if (result.code == "0") {
  //
  // 		}
  // 	});
};


const canEdit = ref(true);
// 编辑
const handleEdit = (row: any, edit: Boolean) => {
      canEdit.value = edit;
      isEdit.value = true;
      formData = reactive({
        ...row
      });
      pickingIdChange(formData.pickingId);
      if (formData.pickingWarehouseId) {
        pickingWarehouseChange(formData.pickingWarehouseId);
      }
      if (formData.pendingWarehouseId) {
        wareChange(formData.pendingWarehouseId, 'pendingList');
      }
      if (formData.inWarehouseId) {
        wareChange(formData.inWarehouseId, 'inWarehouseList');
      }
      // warehouseChange(formData.warehouseId);
      axiosInstance.post('/api/shipmentPlanDetail/getAll', {shipmentPlanId: row.id}).then(res => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        workDetailData.value = res.data;
      });
      showCrud.value = true;
    }
;

const handleConfirm = (row) => {
  ElMessageBox.confirm('是否确认该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.post(`/api/shipmentPlan/config`,
        {
          ids: [row.id]
        }
    ).then(res => {
      ElMessage.success('操作成功');
      getList(); // 刷新数据
    });


  });
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.delete(`/api/shipmentPlan/delete`, {
      data: {
        ids: [row.id]
      }
    }).then(res => {
      ElMessage.success('删除成功');
      getList(); // 刷新数据
    });


  });
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      for (const item of workDetailData.value) {
        if (!item.materialId) {
          ElMessage.error('请选择物料');
          return false;
        }

        if (!item.weight || item.weight == 0) {
          ElMessage.error('请输入重量');
          return false;
        }
        item.workId = formData.workId;
        item.outsourcingId = formData.procedureOrderId;
      }
      formData.shipmentPlanDetailDTO = workDetailData.value;
      if (isEdit.value) {
        // 编辑
        axiosInstance.put('/api/shipmentPlan/update', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      } else {
        // 新建
        formData.outsourcingWorkMaterialDTOS = workDetailData.value;
        axiosInstance.post('/api/shipmentPlan/save', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      }

    }
  });
};


// 模拟 API 调用
const addEquipment = async (data: any) => {
  // 假设这里有一个新建接口
  console.log('新建设备数据:', data);
};

const updateEquipment = async (data: any) => {
  // 假设这里有一个更新接口
  console.log('更新设备数据:', data);
};

const deleteEquipment = async (id: string) => {
  // 假设这里有一个删除接口
  console.log('删除设备ID:', id);
};

const groupBy = (arr, fn) => {
  let group = {};
  arr.map((item) => {
    let type = JSON.stringify(fn(item));
    group[type] = group[type] || [];
    group[type].push(item);
  });

  return Object.keys(group).map((item) => {
    return group[item];
  });
};
</script>
<style scoped>
.content {
}
</style>
